package com.starinside.wp.service.impl;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.starinside.wp.domain.CheckRecord;
import com.starinside.wp.domain.FamilyFeed;
import com.starinside.wp.domain.Feeds;
import com.starinside.wp.domain.Praises;
import com.starinside.wp.domain.observation.ObservationListItemVO;
import com.starinside.wp.domain.observation.ObservationNewQuestionRecord;
import com.starinside.wp.foundation.constant.FeedConstant;
import com.starinside.wp.foundation.dto.StaffDTO;
import com.starinside.wp.foundation.exception.BusinessException;
import com.starinside.wp.foundation.model.ErrorCode;
import com.starinside.wp.foundation.query.base.PagerQuery;
import com.starinside.wp.foundation.vo.*;
import com.starinside.wp.repository.*;
import com.starinside.wp.service.FeedsService;
import com.starinside.wp.service.SsoCallService;
import com.starinside.wp.utils.RemoteCallUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Describle This Class Is
 * @Author ZengMin
 * @Date 2018/11/9 11:00
 * @Company Matt
 */
@Service
public class FeedsServiceImpl implements FeedsService {

    @Autowired
    FeedsRepository feedsRepository;

    @Autowired
    PraisesRepository praisesRepository;

    @Autowired
    PraisesNativeRepository praisesNativeRepository;

    @Autowired
    CheckRecordRepository checkRecordRepository;

    @Autowired
    LiveRecordRepository liveRecordRepository;

    @Autowired
    BirthdayRecordRepository birthdayRecordRepository;

    @Autowired
    BabyNativeRepository babyNativeRepository;

    @Autowired
    private WxParentRepository parentRepository;

    @Autowired
    private FamilyFeedRepository familyFeedRepository;

    @Autowired
    private ChildrenObservationRecordRepository childrenObservationRecordRepository;

    @Autowired
    private ObservationNewQuestionRecordRepository observationNewQuestionRecordRepository;

    @Autowired
    private SsoCallService ssoCallService;

    @Value("${teach.server.url}")
    String teachUrl;

    @Override
    public Map<String, Object> getAllByChildrens(List<BindedBabyVO> childrens, PagerQuery pagerQuery, String uid) {

        if (childrens.size() == 0){
            throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "没有绑定的宝宝");
        }

        List<String> childrensId = childrens.stream().map(BindedBabyVO::getId).collect(Collectors.toList());
        List<String> areaid = childrens.stream().map(BindedBabyVO::getAreaId).collect(Collectors.toList());


        PageRequest pageRequest = PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize());

        List<Feeds> feeds = feedsRepository.findAllByChildrenIdsAndAreaIdIn(childrensId,areaid, pageRequest);

        List<Praises> praises = praisesRepository.findByUidAndFidIn(uid, feeds.stream().map(Feeds::getId).collect(Collectors.toList()));

        //当前用户已点赞的id
        List<String> pfids = praises.stream().map(Praises::getFid).collect(Collectors.toList());
        List<Feeds> feedsResult = Lists.newArrayList();
        feeds.forEach(o -> {
            if (pfids.contains(o.getId())) {
                o.setIsPraises(true);
            } else {
                o.setIsPraises(false);
            }

            feedsResult.add(o);
        });
        long count = feedsRepository.findAllByChildrenIdsAndAreaIdCount(childrensId,areaid);
        PageImpl<Feeds> feeds1 = new PageImpl<>(feedsResult, pageRequest, count);
        ImmutableMap<String, Object> of = ImmutableMap.of("content", feeds1.getContent(), "totalElements",
                feeds1.getTotalElements(), "totalPages", feeds1.getTotalPages(), "last", pageRequest.getPageNumber() + 1 == feeds1.getTotalPages());
        return of;
    }

    @Override
    public Feeds postFeeds(String parentId,  String childrenId, String title, String content, String resources, Integer mediaType){

        BindedBabyVO children = babyNativeRepository.getBindedBabyById(childrenId, parentId);

        if(children == null){
            throw new BusinessException("没有指定宝宝");
        }

        WxParent parent = parentRepository.findParentBy(childrenId, parentId);

        //创建familyFeed
        FamilyFeed ff = new FamilyFeed();
        ff.setChildrenId(childrenId);
        ff.setChildrenName(children.getNickName());
        ff.setUid(parent.getParentUserId());
        ff.setUname(parent.getParentName());
        ff.setMedias(resources);
        ff.setMediaType(mediaType);
        ff.setTitle(title);
        ff.setContent(content);

        familyFeedRepository.save(ff);

        //创建Feed
        Feeds f = new Feeds();
        f.setTitle(title);
        f.setContent(content);
        f.setUid(parent.getParentUserId());
        f.setChildrenId(childrenId);
        f.setPlace(children.getAreaId());
        f.setEvent(FeedConstant.FAMILY_FEED + "");
        f.setEventType(FeedConstant.FAMILY_FEED_TYPE);
        f.setTitle(title);
        f.setContent(content);

        if(mediaType == 0){
            f.setImages(resources);
        }else if (mediaType == 1){
            f.setVideos(resources);
        }

        f.setType(FeedConstant.FAMILY_FEED);
        f.setTypeVal("家长时光轴");

        f.setLinkId(ff.getId());

        feedsRepository.save(f);

        return f;
    }

    @Override
    public boolean addPraise(String uid, String fid) {
        Praises praises = praisesRepository.findByUidAndFid(uid, fid);
        if(!Objects.isNull(praises)){
            throw new BusinessException(ErrorCode.ALREADY_PRAISES_ERROR,"你已经点过赞了！");
        }
        Praises save = praisesRepository.save(Praises.of(uid, fid));
        return save != null;
    }

    @Override
    public boolean deletePraise(String uid, String fid) {
        int i = praisesRepository.deleteByUidAndFid(uid, fid);
        return i>0;
    }

    @Override
    public Feeds getOne(String id) {
        try {
            Feeds feeds = feedsRepository.getOne(id);
            return feeds;
        }catch (Exception e){
            throw new BusinessException(ErrorCode.SIGN_ERROR,"动态不存在！");
        }
    }

    @Override
    public Map getOne(String id, String uid) {
        try {
            Feeds feeds = feedsRepository.getOne(id);

            List<PraisesVO> praises = praisesNativeRepository.findByUidAndFid(uid, id);

            if(!StringUtils.isEmpty(uid)) {
                praises.forEach(o -> {
                    if (uid.equals(o.getUid())) {
                        feeds.setIsPraises(true);
                    }
                });
            }

            if (feeds.getIsPraises() == null){
                feeds.setIsPraises( false );
            }

            Map<String, Object> result = new HashMap<>();

            result.put("feed", feeds);
            result.put("praises", praises);

            return result;
        }catch (Exception e){
            throw new BusinessException(ErrorCode.SIGN_ERROR,"动态不存在！");
        }
    }

    @Override
    public Object getDetailEvaluate(String linkId) {
        HashMap data = RemoteCallUtil.call(teachUrl + FeedConstant.FEEDS_TYPE_URL.NURSERY_MONTH_EVALUATE.getUrl(), ImmutableMap.of("evaluateRecordId", linkId), null, HashMap.class, "教务系统 通讯异常");
        Map ret = new HashMap<String, Objects>();

        if (null != data) {
            Map<String, Object> map = (Map<String, Object>) data;
            ret.put("record", map);
            ret.put("adviseTag", map.get("adviseTag"));
            ret.put("recommendPlanTag", map.get("recommendPlanTag"));
        }

        return ret;
    }

    @Override
    public Object getDetailPlanCourse(String childrenId, PagerQuery pagerQuery) {
        Object call = RemoteCallUtil.call(teachUrl + FeedConstant.FEEDS_TYPE_URL.PLAN_COURSE.getUrl(),
                ImmutableMap.of("childrenId", childrenId, "pageNum", pagerQuery.getPageNum(), "pageSize", pagerQuery.getPageSize()), null, Map.class, "教务系统 通讯异常");
        return call;
    }

    @Override
    public Object getLinkedObjects(String feedId, String childrenId, PagerQuery pagerQuery){

        Feeds f = getOne(feedId);

        int value = Integer.parseInt(f.getEventType());

        Object result = null;

        switch (value){
            case FeedConstant.HEALTH_CHECK: //晨检签到
            {
                CheckRecord record = checkRecordRepository.getOne(f.getLinkId());

                result = record;
            }
            break;
            case FeedConstant.NURSERY: //托班观测记录
            {
                result = liveRecordRepository.getOne(f.getLinkId());
            }
            break;
            case FeedConstant.NURSERY_MONTH_EVALUATE: //托班月评
            {
                result = getDetailEvaluate(f.getLinkId());
            }
            break;
            case FeedConstant.PLAN_COURSE: //排课
            {
                result = getDetailPlanCourse(childrenId, pagerQuery);
            }
            break;
            case FeedConstant.STA_EVALUATE_END: //SAT课堂评测
            {

            }
            break;
            case FeedConstant.STA_EVALUATE_MONTH: //SAT月评
            {
                // matt baby plus 项目内和  NURSERY_MONTH_EVALUATE  是同一个位置，奇怪
                result = getDetailEvaluate(f.getLinkId());
            }
            break;
            case FeedConstant.BIRTHDAY_MEETING: //园区生日会
            {
                birthdayRecordRepository.getOne(f.getLinkId());
            }
            break;
            case FeedConstant.EVALUATE_RECORD: //评测报告
            {
                result = getDetailEvaluate(f.getLinkId() );
            }
            break;
            case FeedConstant.OBSERVATION_NEW: //课堂观测点报告
            {
                String id = f.getLinkId();
                ObservationListItemVO object = childrenObservationRecordRepository.findByRecordId(id);

                List<ObservationNewQuestionRecord> questions = observationNewQuestionRecordRepository.findAllQuestionGroupedByTitle(id);

                object.setQuestions(questions);

                result = object;
            }
            break;
        }

        return result;
    }

    @Transactional
    @Override
    public Feeds save(String staffId, String childrenId, String areaId, String event, String eventType, String title, String content, String images, String videos, String linkId) {

        StaffDTO teacherInfo = ssoCallService.getStaffDTO(null, staffId);

        Feeds f = Feeds.of(staffId, childrenId, areaId, event, eventType, title, content, images, videos, linkId,"");

        f.setTeacherName(teacherInfo.getRealName());
        f.setTeacherImg(teacherInfo.getHeadImgUrl());

        Feeds feeds = feedsRepository.saveAndFlush(f);
        return feeds;
    }
}
